package com.example.sensor.slice;

import com.example.sensor.ResourceTable;
import com.example.sensor.Utils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Image;
import ohos.sensor.agent.CategoryOrientationAgent;
import ohos.sensor.agent.SensorAgent;
import ohos.sensor.bean.CategoryOrientation;
import ohos.sensor.data.CategoryOrientationData;
import ohos.sensor.listener.ICategoryOrientationDataCallback;

public class CompassAbilitySlice extends AbilitySlice {
    // 指南针Image组件
    private Image mImageCompass;
    // 方向类传感器代理
    private CategoryOrientationAgent mOrientationAgent;
    // 方向类传感器
    private CategoryOrientation mOrientation;


    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_compass);
        // 获取Image对象
        mImageCompass = (Image) findComponentById(ResourceTable.Id_image_compass);
        // 创建方向类传感器的代理对象
        mOrientationAgent = new CategoryOrientationAgent();
        // 获取方向传感器
        mOrientation = mOrientationAgent.getSingleSensor(
                CategoryOrientation.SENSOR_TYPE_ORIENTATION);
        // 订阅方向传感器
        mOrientationAgent.setSensorDataCallback(
                mOrientationDataCallback, mOrientation, SensorAgent.SENSOR_SAMPLING_RATE_UI);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // 退订方向传感器
        mOrientationAgent.releaseSensorDataCallback(
                mOrientationDataCallback, mOrientation);
    }
    // 方向类传感器数据回调
    private ICategoryOrientationDataCallback mOrientationDataCallback = new ICategoryOrientationDataCallback() {
        @Override
        public void onSensorDataModified(CategoryOrientationData categoryOrientationData) {
            // 获取数据
            final float[] values = categoryOrientationData.values;
            // 第1个参数即为偏离正北的方向数据
            getUITaskDispatcher().asyncDispatch(()-> {
                mImageCompass.setRotation(-values[0]);
            });
        }
        @Override
        public void onAccuracyDataModified(CategoryOrientation categoryOrientation, int i) {
        }

        @Override
        public void onCommandCompleted(CategoryOrientation categoryOrientation) {
        }
    };
}
